import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/services.dart';
import 'package:flutter_plugin/base/controller/base_controller.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import '../../../constant/env.dart';
import '../../../constant/sp_key.dart';
import '../../../ext/get_extension.dart';
import '../../../net/api_respository.dart';
import '../../../net/data/login_data.dart';
import '../../../net/http_url.dart';
import '../../../res/colors.dart';
import '../../../res/style.dart';
import '../../../res/text_style.dart';
import '../../../routes/router.dart';
import '../../../routes/router_util.dart';
import '../../../util/aes_utils.dart';
import '../../../util/sputil.dart';
import '../../../util/string_util.dart';
import 'login_psw_state.dart';

class LoginPswLogic extends BaseController<LoginPswLogic> {
  final LoginPswState state = LoginPswState();

  @override
  void loadNet() {
    // TODO: implement loadNet
  }

  void checkLoginText() {
    if (state.unameController.text.isNotEmpty && state.pswController.text.isNotEmpty) {
      state.isBtnEnabled.value = true;
    } else {
      state.isBtnEnabled.value = false;
    }
  }

  void login(String phone, String psw) {
    if (!StringUtil.isPhone(phone)) {
      GetExtension.showCommonDialog(content: "请输入正确的手机号码", negaVisible: false, posiTap: () {});
      return;
    }

    if (!StringUtil.isPsw(psw)) {
      GetExtension.showCommonDialog(content: "密码必须是8-16位，包含字母、数字、符号组合；请重新输入", negaVisible: false, posiTap: () {});
      return;
    }

    if (state.privacyCheck.value) {
      loadLogin(phone, psw);
    } else {
      GetExtension.showCommonDialog(
        title: "使用前须同意",
        negaText: "不同意",
        posiText: "同意并继续",
        centerWidget: Column(
          children: [
            RichText(
              textAlign: TextAlign.center,
              text: TextSpan(
                  style: TextStyle(
                    fontWeight: FontWeight.w400,
                    fontSize: 16.sp,
                  ),
                  children: [
                    // 为了保障您的合法权益，请阅读并同意
                    TextSpan(
                      text: "为了保障您的合法权益，请阅读并同意",
                      style: Styles.style_FF666666,
                    ),
                    TextSpan(
                        text: "《用户协议》",
                        style: Styles.style_FF00A1FF,
                        recognizer: TapGestureRecognizer()
                          ..onTap = () {
                            RouterUtil.toWebPage("用户协议", Env.envConfig.userAgreementUrl);
                          }),
                    TextSpan(
                      text: "和",
                      style: Styles.style_FF666666,
                    ),
                    TextSpan(
                        text: "《隐私协议》",
                        style: Styles.style_FF00A1FF,
                        recognizer: TapGestureRecognizer()
                          ..onTap = () {
                            RouterUtil.toWebPage("隐私声明 ", Env.envConfig.privacyPolicyUrl);
                          }),
                  ]),
            ),
            Container(
              alignment: Alignment.center,
              margin: EdgeInsets.only(top: 13.h),
              child: Text(
                "臻情守护家人将严格保护你的个人信息安全",
                textAlign: TextAlign.center,
                style: TextStyles.textStyle(ColorStyle.color_FF303030, 14.sp, fontWeight: FontWeight.w600),
              ),
            ),
          ],
        ),
        posiTap: () {
          state.privacyCheck.value = true;
          debugPrint("============posiTap");
          loadLogin(phone, psw);
        },
        negaTap: () {
          state.privacyCheck.value = false;
          debugPrint("============posiTap");
        },
      );
    }
  }

  void loadLogin(String phone, String psw) {
    SystemChannels.textInput.invokeMethod('TextInput.hide');
    var queryParameters = <String, dynamic>{};
    queryParameters['phone'] = AesUtils.encryptAes(plainText: phone);
    queryParameters['password'] = AesUtils.encryptAes(plainText: psw);
    ApiRepository.instance.request<LoginData>(HttpUrl.login,
        params: queryParameters, withLoading: true, loadText: '登陆中…', success: (loginData) {
      SPUtil.instance.put(SPKey.phone_input, phone);
      SPUtil.instance.put(SPKey.TOKEN, loginData.token!);
      SPUtil.instance.put(SPKey.phone, loginData.user!.phone!);
      SPUtil.instance.put(SPKey.name, loginData.user!.name!);
      SPUtil.instance.put(SPKey.avatar, loginData.user!.avatar!);
      SPUtil.instance.put(SPKey.notSetPassword, loginData.notSetPassword!);
      SPUtil.instance.put(SPKey.isLogin, true);
      SPUtil.instance.put(SPKey.uid, loginData.user!.uid!);
      Get.offAllNamed(AppRoutes.home);
    }, error: (e) {
      showToast(e.message ?? "登录失败");
    });
  }
}
